package org.nettyServer.messageHandle.login;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.nettyServer.command.CommandBase;
import org.nettyServer.command.login.CS_Login;
import org.nettyServer.command.login.SC_Login;
import org.nettyServer.connectionManage.ClientInfo;
import org.nettyServer.connectionManage.ConnectionManage;
import org.nettyServer.connectionManage.NotRegisterClientInfo;
import org.nettyServer.eunm.EMessageCode;
import org.nettyServer.eunm.EResCode;
import org.nettyServer.messageHandle.MessageHandleBase;
import org.nettyServer.messageHandle.PushUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.function.Supplier;

@Service
@Slf4j
public class LoginLogic implements MessageHandleBase {

    @Override
    public void handle(CommandBase commandBase, Channel channel) {
        CS_Login csLogin = JSON.parseObject(commandBase.getData(), CS_Login.class);
        if (csLogin.getUserName().equals("admin") ) {

            // 登录成功获取未注册连接
            NotRegisterClientInfo clientInfoFromNotRegisterClient =
                    ConnectionManage.getClientInfoFromNotRegisterClient(channel);
            if (Objects.isNull(clientInfoFromNotRegisterClient)){
                log.info("客户端登录未查询到连接信息");
                return;
            }
            // 移除未注册连接
            ConnectionManage.removeNotRegisterClientInfo(channel);

            // 加入已注册连接
            ClientInfo clientInfo = ClientInfo
                    .builder()
                    .ip(clientInfoFromNotRegisterClient.getIp())
                    .port(clientInfoFromNotRegisterClient.getPort())
                    .channel(channel)
                    .lastActiveTime(System.currentTimeMillis())
                    .connectTime(clientInfoFromNotRegisterClient.getConnectTime())
                    .build();
            ConnectionManage.addClientInfo(clientInfo);

            //对登陆回应
            SC_Login scLogin = SC_Login.builder()
                    .code(EResCode.SUCCESS.getCode())
                    .build();
            PushUtils.pushMessage(EMessageCode.LOGIN.getCode(),scLogin, channel);
        }
    }
}
